package com.example.demo.service.impl;

import com.example.demo.config.shiro.AdminUserToken;
import com.example.demo.config.shiro.CommonUserToken;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author: yucsa
 * @Date: 2021/8/22 23:03
 */

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public User findByName(String userName) {
        return userMapper.findByName(userName);
    }

    @Override
    public User findById(Long id) {
        return userMapper.findById(id);
    }

    /**
     * @yucs 把注册放到service中实现
     * @param username 用户设置的用户名
     * @param password
     * @return 要返回的页面；告诉controller，让controller控制跳转
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public String register(String username, String password) {
        String targetPage = null;
        User sameNameUser = userMapper.findByName(username);
        if(sameNameUser!=null){
            System.out.println("用户名已存在！");
            targetPage = "index";
        }
        User regUser = new User(username,password);
        userMapper.addRegUser(regUser);
        long userId = regUser.getId();

        System.out.println("您的系统Id是： " + userId + "；现在还是用户名+密码奥");
        targetPage =  "index";

        return targetPage;
    }

    /**
     * 插入一个新用户，返回插入用户的id
     * @param
     * @return 插入用户的id，用于告知用户，使用该id登录
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Integer addRegUser(User regUser) {
        Integer insertId = userMapper.addRegUser(regUser);
        return insertId;
    }

    /**
     * @yucs,登出换到service中，仍旧使用shiro实现
     * @return
     */
    @Override
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()){
            subject.logout();
        }
        return "index";
    }

    @Override
    public String login(String username, String password, String type, HttpSession httpSession) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = null;
        String target = null;
        //用于存放用户角色，登录完成后放到session中；
        String loginRole = null;
        switch (type){
            case "user":
                token = new CommonUserToken(username,password);
                break;
            case "admin":
                token = new AdminUserToken(username,password);
                break;
            default:
                break;
        }

        try{
            subject.login(token);
            //在session中存放用户和管理员的名字，放在首页做欢迎；
            httpSession.setAttribute("role",loginRole);
            httpSession.setAttribute("name",username);
            target = "hello";
        }catch (UnknownAccountException e){
            target = "login";
        }catch (IncorrectCredentialsException e){
            target = "login";
        }

        return target;

    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public List<User> queryUserList(Integer index, Integer limit) {
        return userMapper.queryUserList(index,limit);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Integer updateUser(User user) {
        return userMapper.updateUser(user);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Integer deleteUser(Long id) {
        return userMapper.deleteUser(id);
    }

}
